package sw6.visualschedule.adminpanel;

import com.commonsware.cwac.sacklist.SackOfViewsAdapter;

import sw6.visualschedule.R;
import sw6.visualschedule.entities.Day;
import sw6.visualschedule.entities.RepeatPattern;
import sw6.visualschedule.entities.ScheduleActivity;
import sw6.visualschedule.extendedViews.CustomEntry;
import sw6.visualschedule.extendedViews.SeperatorEntry;
import sw6.visualschedule.persistence.RepeatPatternRepo;
import sw6.visualschedule.persistence.ScheduleActivityRepo;
import tools.BundleHelper;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.ListView;
import android.widget.TimePicker;
import android.widget.Toast;

import java.util.ArrayList;

/**
 * The activity which manages the creation of new repeat patterns 
 * @author SW6E
 */
public class RepeatPatternConstructor extends ListActivity {
	
	//Entry constants
	// 0 is reserved for "required" separator
	final private static int DAYINWEEK_ENTRY = 1;
	final private static int TIMEOFDAY_ENTRY = 2;
	
	//Database
	private ScheduleActivityRepo mActivityService;
	private RepeatPatternRepo mRepeatPatternService;
	
	//Object
	private ScheduleActivity mActivity;
	private RepeatPattern mRepeatPattern;
	private int mActivityId;
	private int mRepeatPatternId;
	
	//Entries
	private CustomEntry mDayInWeekEntry;
	private CustomEntry mTimeOfDayEntry;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.constructor_layout_list);
		
		mActivityService = new ScheduleActivityRepo(this);
		mRepeatPatternService = new RepeatPatternRepo(this);
		
		//Get Activity
		mActivityId = getIntent().getIntExtra(BundleHelper.ACTIVITY_ID, -1);
		mActivity = mActivityService.getById(mActivityId);
		
		mRepeatPatternId = getIntent().getIntExtra(BundleHelper.REPEAT_PATTERN_ID, -1);
		
		if (savedInstanceState == null && mRepeatPatternId == -1){
			//The user wants to create a new repeat pattern
			mRepeatPattern = new RepeatPattern(mActivity);
			mRepeatPatternService.create(mRepeatPattern);
			mRepeatPatternId = mRepeatPattern.getId();
		} else if (savedInstanceState != null){
			//The user wants to edit an existing activity
			setTitle(getString(R.string.adm_repeatpatternconstructor_title_edit));
			mRepeatPatternId = savedInstanceState.getInt(BundleHelper.REPEAT_PATTERN_ID);
		}
	}
	@Override
	protected void onResume() {
		super.onResume();

		mRepeatPattern = mRepeatPatternService.getById(mRepeatPatternId);
		
		ArrayList<View> views = new ArrayList<View>();
		
		//Required separator
		
		views.add(new SeperatorEntry(this, getString(R.string.constructor_required)));
		
		// Day in week
		mDayInWeekEntry = new CustomEntry(this);
		mDayInWeekEntry.getTitle().setText(getString(R.string.adm_repeatpatternconstructor_dayinweek));
		
		// Time of day
		mTimeOfDayEntry = new CustomEntry(this);
		mTimeOfDayEntry.getTitle().setText(getString(R.string.adm_repeatpatternconstructor_timeofday));
		
		views.add(DAYINWEEK_ENTRY, mDayInWeekEntry);
		views.add(TIMEOFDAY_ENTRY, mTimeOfDayEntry);
		
		updateDisplay();
		
		setListAdapter(new SackOfViewsAdapter(views));
	}
	
	@Override
	protected void onListItemClick(final ListView list, final View view, final int position, final long itemId) {
		
		switch (position) {
		    
    		case DAYINWEEK_ENTRY:
    		    final AlertDialog.Builder alert = new AlertDialog.Builder(RepeatPatternConstructor.this);
    			
    			final CharSequence[] items = { Day.MONDAY.toString(), Day.TUESDAY.toString(), Day.WEDNESDAY.toString(), Day.THURSDAY.toString(), Day.FRIDAY.toString(), Day.SATURDAY.toString(), Day.SUNDAY.toString()};
    			
    			alert.setTitle(getString(R.string.adm_repeatpatternconstructor_choosedayinweek));
    			alert.setItems(items, new DialogInterface.OnClickListener() {
    			    public void onClick(final DialogInterface dialog, final int item) {
    			        mRepeatPattern.setDayInWeek(Day.values()[item]);
    			        mRepeatPatternService.update(mRepeatPattern);
    			        updateDisplay();
    			    }
    			});
    			    			
    			alert.create().show();
    			
    			break;
    			
    		case TIMEOFDAY_ENTRY:
    		    
    		    final TimePickerDialog dialog = new TimePickerDialog(
    		            RepeatPatternConstructor.this,
    		            new TimePickerDialog.OnTimeSetListener() {
    		                public void onTimeSet(final TimePicker view, final int hourOfDay, final int minute) {
    		                    mRepeatPattern.setHourOfTheDay(hourOfDay);
    		                    mRepeatPattern.setMinuteOfTheHour(minute);
    		                    mRepeatPatternService.update(mRepeatPattern);
    		                    
    		                    updateDisplay();
    		                }
    		            },
    		            mRepeatPattern.getHourOfTheDay(),
    		            mRepeatPattern.getMinuteOfTheHour(),
    		            true);
    		    dialog.show();
    		    
    		    break;
    		default:
    			break;
    	}
	}
    
	public void superOnBackPressed() {
        super.onBackPressed();
    }
	
	@Override
    public void onBackPressed() {
	    String error = "";
	    
	    if (mRepeatPattern.getDayInWeek() == null) {
	        error = getString(R.string.adm_repeatpatternconstructor_dayinweekrequired);
	    }
	    
        if ("".equals(error)) {
            super.onBackPressed();
            
            Toast.makeText(this, R.string.adm_repeatpatternconstructor_saved, Toast.LENGTH_SHORT).show();
        } else {
            final AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(R.string.constructor_confirmation);
            builder.setMessage(getString(R.string.adm_repeatpatternconstructor_error_save) + "\n" + error);
            builder.setPositiveButton(getString(R.string.adm_repeatpatternconstructor_delete_quit), new OnClickListener() {
                
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    RepeatPatternConstructor.this.superOnBackPressed();
                    Toast.makeText(RepeatPatternConstructor.this, R.string.adm_repeatpatternconstructor_deleted, Toast.LENGTH_SHORT).show();
                    mRepeatPatternService.delete(mRepeatPattern);
                }
            });
            
            builder.setNegativeButton(getString(R.string.adm_repeatpatternconstructor_edit_stay), null);
            builder.show();
        }
    }
	
    private void updateDisplay() {
        if (mRepeatPattern.getDayInWeek() != null) {
            mDayInWeekEntry.getSummary().setText(mRepeatPattern.getDayInWeek().toString());
        }
        
        if (mRepeatPattern.getHourOfTheDay() != 0 || mRepeatPattern.getMinuteOfTheHour() != 0) {
            mTimeOfDayEntry.getSummary().setText(getString(R.string.adm_repeatpatternconstructor_timesummary, mRepeatPattern.getHourOfTheDay(), mRepeatPattern.getMinuteOfTheHour()));
        }
    }
	
	public void onSaveInstanceState(final Bundle savedInstanceState) {
		// Save UI state changes to the savedInstanceState.
		// This bundle will be passed to onCreate if the process is
		// killed and restarted.
		savedInstanceState.putInt(BundleHelper.ACTIVITY_ID, mActivity.getId());
		savedInstanceState.putInt(BundleHelper.REPEAT_PATTERN_ID, mRepeatPattern.getId());
		super.onSaveInstanceState(savedInstanceState);
	}
}
